import { cleanEnv, port, str, url } from 'envalid'
import { EnvVars } from '../types/env'

declare const process: NodeJS.Process

export const validateEnv = (): EnvVars => {
  try {
    const env = cleanEnv(process.env, {
      NODE_ENV: str({
        choices: ['development', 'production', 'test'],
        default: 'development',
      }),
      PORT: port({
        default: 3001,
        desc: 'Port number for the server',
      }),
      MONGODB_URI: url({
        default: 'mongodb://localhost:27017/live-platform',
        desc: 'MongoDB connection string',
      }),
      JWT_SECRET: str({
        desc: 'JWT secret key for authentication',
        devDefault: 'development-jwt-secret',
      }),
      CLIENT_URL: str({
        default: 'http://localhost:3000',
        desc: 'Client application URL',
      }),
      STREAM_SECRET: str({
        desc: 'Secret key for stream authentication',
        devDefault: 'development-stream-secret',
      }),
    }) as EnvVars

    return env
  } catch (error) {
    console.error('Environment validation failed:', error)
    ;(process as NodeJS.Process).exit(1)
    throw error // 确保函数有返回值
  }
}

export const envVars = validateEnv()
